﻿using Newtonsoft.Json;
using SpeechLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DouYinFiddlerPlugin
{

   

    public class SocketUtils
    {
        public UserControl1 userControl1 { get; set; }
        private Socket socket = null;
        private Task task = null;
        private Task task2 = null;
        public bool coonected = false;

        JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            DateFormatString = "yyyy-MM-dd HH:mm:ss"

        };


        public void Connect()
        {


            if (socket != null && socket.Connected)
            {
                return;
            }

            SpVoice voice = new SpVoice();
            voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0);
          

            IPAddress ip = IPAddress.Parse("127.0.0.1");//接收端所在IP
            IPEndPoint ipEnd = new IPEndPoint(ip, 9200);//接收端所监听的接口
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化一个Socket对象
            socket.SendTimeout = 2000;
           

            try
            {
                userControl1.addLog("连接...." );
                /* if (socket != null && socket.Connected)
                 {
                     Shutdown();

                 }*/

                socket.Connect(ipEnd);//连接指定IP&端口
                userControl1.addLog("成功....");
                coonected = true;

            }
            catch (SocketException e)
            {
                Console.WriteLine("连接失败");
            //    MessageBox.Show("连接到解析服务失败!","错误");
                Console.WriteLine(e.ToString());
                userControl1.addLog("连接到解析服务失败!"+e.Message);
                coonected = false;
                Task.Run(() => {
                    voice.Speak("连接到解析服务失败!请确保decoding.exe程序正常运行!正在重试!", SpeechVoiceSpeakFlags.SVSFDefault);
                });
                return;
            }
          
            if (null != task)
            {
                task.Dispose();
            }

            redata();

        }


        public void redata()
        {
           task = Task.Run(() =>
            {

                while (true)//定义一个循环接收返回数据
                {
                    if (!socket.Connected)
                    {
                        break;
                    }

                    byte[] data = new byte[999999];
                    socket.Receive(data);//接收返回数据
                    string stringData = Encoding.UTF8.GetString(data);
                    if (!string.IsNullOrWhiteSpace(stringData))
                    {
                       // userControl1.setTextBox("数据:" + stringData);
                        JsonDe(stringData);
                        Console.Write(stringData);
                       // break;
                    }
                }

            });
        }



        public void JsonDe(string json)
        {


            try
            {
                dynamic data = JsonConvert.DeserializeObject<dynamic>(json, jsonSerializerSettings);
               
                if (data != null && data["status"].Value)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in data["data"])
                    {
                        sb.Clear();
                        switch (item["common"]["method"].ToString())
                       {
                            case "WebcastChatMessage"://弹幕
                                
                                sb.Append(item["user"]["nickname"]);
                                sb.Append(" 说: ");
                                sb.Append(item["content"]);
                                break;
                            case "WebcastGiftMessage"://礼物
                          
                                sb.Append(item["common"]["describe"]);
                                break;
                            case "WebcastFansclubMessage"://粉丝团
                                sb.Append(item["content"]);
                                break;
                            case "WebcastMemberMessage"://进入直播间
              
                                sb.Append(item["user"]["nickname"]);
                                sb.Append(" 进入直播间 ");

                                break;
                            case "WebcastLiveShoppingMessage"://购物车消息
                
                                sb.Append("购物信息");
                               // sb.Append(item);
                                break;
                            case "WebcastLikeMessage"://点赞
                         
                                sb.Append(item["user"]["nickname"]);
                                sb.Append(" 为主播点赞 ");
                                break;
                            case "WebcastSocialMessage"://关注主播
                               
                                sb.Append(item["user"]["nickname"]);
                                sb.Append(" 关注了主播: ");
                                break;

                            default:
                                break;
                       }

                        userControl1.addTextBox(sb.ToString());
                        TaskSpeak(sb.ToString());

                    }
                    
                }


            } catch (Exception ex)
            {
                userControl1.addLog("数据解析失败:" + ex.Message);

            }



        }

        /// <summary>
        /// 在子线程里调用win讲述人播报
        /// </summary>
        /// <param name="data"></param>
        public void TaskSpeak(string data)
        {
            //判断是否已经处于播报中
            if (task2  != null && !task2.IsCompleted)
            {
                return;
            }
            if (userControl1.getCheck())
            {
                return;
            }

            task2 = Task.Run(() =>
            {
                try
                {   //播报语音
                    SpVoice voice = new SpVoice();
                    voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0);
                    voice.Speak(data, SpeechVoiceSpeakFlags.SVSFDefault);
                }
                catch (Exception ex)
                {
                    userControl1.addLog(ex.Message);
                }
              

            });
        }


        public bool Connected()
        {
            //socket.Connected
            return socket.Connected;
        }


        public void Send(byte[] data)
        {

            try
            {
                if (socket.Connected)
                {
                    socket.Send(data);//发送数据
                }

            }
            catch (Exception e)
            {
                userControl1.addLog("数据发送错误:" + e.Message);
                Connect();
            }  
        }


        public void Shutdown()
        {
            coonected = false;
              socket.Shutdown(SocketShutdown.Both);
              socket.Close();//关闭Socket
        }


    }
}
